<template>
  <div class="home">
    <el-input
      type="textarea"
      :rows="2"
      placeholder="请输入内容"
      v-model="wordData.textarea"
    >
    </el-input>
    <el-button type="primary" plain @click="frontDownload"
      >点击下载模板</el-button
    >
  </div>
</template>

<script>
// @ is an alias to /src
import { exportWord, getBase64Sync } from "@/utils/exportFile";
export default {
  name: "Home",
  data() {
    return {
      wordData: {
        name: "测试",
        textarea: "",
        thinglist: [
          { name: "测试", thing: "上班" },
          { name: "测试", thing: "下班" },
        ],
        imglist: [
          {
            imgUrl: "file/微信图片_20220209193410.jpg",
          },
          {
            imgUrl: "file/1640766512(1).png",
          },
        ],
        imgSize: [],
      },
    };
  },
  computed: {},

  watch: {},
  created() {},

  methods: {
    async frontDownload() {
      try {
        this.wordData.imglist.forEach(async (x, i) => {
          // 获取图片
          let imgObj = new Image();
          imgObj.src = x.imgUrl;
          // onload 里面访问不到this  此处定义常量指向this
          const that = this;
          // 防止图片过大加载速度过慢问题
          imgObj.onload = async () => {
            // 获取图片宽高
            const res = {
              width: imgObj.width,
              height: imgObj.height,
            };
            // 基于A4纸对超出大小的图片宽高进行等比例缩放
            if (res.width > 595 && res.height <= 842) {
              const v = res.width / 595;
              res.width = 595;
              res.height = res.height / v;
            } else if (res.width <= 595 && res.height > 842) {
              const v = res.height / 842;
              res.height = 842;
              res.width = res.width / v;
            } else if (res.width > 595 && res.height > 842) {
              const v1 = res.width / 595;
              const v2 = res.height / 842;
              if (v1 >= v2) {
                res.width = 595;
                res.height = res.height / v1;
              } else {
                res.height = 842;
                res.width = res.width / v2;
              }
            }
            // 为每一个图片输入缩放后的宽高 --- 此处为二维数组
            that.wordData.imgSize.push(Object.values(res));
            // 进行 base64 格式转换
            this.wordData.imglist[i].imgUrl = await getBase64Sync(
              this.wordData.imglist[i].imgUrl
            );
            // 当所有图片都循环完并算完宽高后再调用下载模板
            if (i === that.wordData.imglist.length - 1) {
              // 处理 textarea 换行问题
              that.wordData.textarea = that.wordData.textarea.split("\n");
              exportWord(
                "file/模板.docx", // 模板路径
                that.wordData, // 数据
                "导出模板.docx", // 模板名字
                that.wordData.imgSize // 图片宽高
              );
            }
          };
        });
      } catch (error) {
        console.log(error);
      }
    },
  },

  mounted() {},
};
</script> 

<style scoped lang="less">
</style>
